package com.zky.controller;

import cn.hutool.core.lang.UUID;
import com.zky.dao.DiseaseDao;
import com.zky.domain.dto.DiseaseRequestDto;
import com.zky.domain.po.Disease;
import com.zky.domain.po.PageResult;
import com.zky.domain.po.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("disease")
@Api(tags = "疾病登记接口")
@RequiredArgsConstructor
public class DiseaseController {

    private final DiseaseDao diseaseDao;

    @ApiOperation("分页查询")
    @GetMapping
    public Result list(DiseaseRequestDto dto) {
        List<Disease> all = diseaseDao.getAll();
        List<Disease> filtered = new ArrayList<>();

        for (Disease d : all) {
            if (dto.getCattleNumber() != null && !dto.getCattleNumber().isEmpty()
                    && (d.getCattleNumber() == null || !d.getCattleNumber().contains(dto.getCattleNumber()))) {
                continue;
            }
            if (dto.getDiseaseName() != null && !dto.getDiseaseName().isEmpty()
                    && (d.getDiseaseName() == null || !d.getDiseaseName().contains(dto.getDiseaseName()))) {
                continue;
            }
            if (dto.getCuredStatus() != null && !dto.getCuredStatus().isEmpty()
                    && (d.getCuredStatus() == null || !dto.getCuredStatus().equals(d.getCuredStatus()))) {
                continue;
            }
            if (dto.getOwner() != null && !dto.getOwner().isEmpty()
                    && (d.getOwner() == null || !dto.getOwner().equals(d.getOwner()))) {
                continue;
            }
            // 日期范围筛选（发病日期）
            if (dto.getStartDate() != null && !dto.getStartDate().isEmpty()) {
                LocalDate start = LocalDate.parse(dto.getStartDate());
                if (d.getOnsetDate() == null || d.getOnsetDate().isBefore(start)) {
                    continue;
                }
            }
            if (dto.getEndDate() != null && !dto.getEndDate().isEmpty()) {
                LocalDate end = LocalDate.parse(dto.getEndDate());
                if (d.getOnsetDate() == null || d.getOnsetDate().isAfter(end)) {
                    continue;
                }
            }
            filtered.add(d);
        }

        int start = (dto.getPageNo() - 1) * dto.getPageSize();
        List<Disease> page = new ArrayList<>();
        for (int i = start; i < start + dto.getPageSize(); i++) {
            if (i < filtered.size()) {
                page.add(filtered.get(i));
            } else {
                break;
            }
        }
        return PageResult.of(page, filtered.size());
    }

    // 兼容前端 /disease/list 路径
    @ApiOperation("分页查询（兼容路径）")
    @GetMapping("/list")
    public Result listAlias(DiseaseRequestDto dto) {
        return list(dto);
    }

    @ApiOperation("统计：总数/已治愈/未治愈")
    @GetMapping("/stats")
    public Result stats(DiseaseRequestDto dto) {
        List<Disease> all = diseaseDao.getAll();
        int total = 0;
        int cured = 0;
        int uncured = 0;

        for (Disease d : all) {
            // 复用与列表相同的过滤逻辑（简化：只按关键条件过滤）
            if (dto.getCattleNumber() != null && !dto.getCattleNumber().isEmpty()
                    && (d.getCattleNumber() == null || !d.getCattleNumber().contains(dto.getCattleNumber()))) {
                continue;
            }
            if (dto.getDiseaseName() != null && !dto.getDiseaseName().isEmpty()
                    && (d.getDiseaseName() == null || !d.getDiseaseName().contains(dto.getDiseaseName()))) {
                continue;
            }
            if (dto.getOwner() != null && !dto.getOwner().isEmpty()
                    && (d.getOwner() == null || !dto.getOwner().equals(d.getOwner()))) {
                continue;
            }
            if (dto.getStartDate() != null && !dto.getStartDate().isEmpty()) {
                LocalDate start = LocalDate.parse(dto.getStartDate());
                if (d.getOnsetDate() == null || d.getOnsetDate().isBefore(start)) {
                    continue;
                }
            }
            if (dto.getEndDate() != null && !dto.getEndDate().isEmpty()) {
                LocalDate end = LocalDate.parse(dto.getEndDate());
                if (d.getOnsetDate() == null || d.getOnsetDate().isAfter(end)) {
                    continue;
                }
            }

            total++;
            if ("已治愈".equals(d.getCuredStatus())) cured++;
            if ("未治愈".equals(d.getCuredStatus())) uncured++;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("cured", cured);
        map.put("uncured", uncured);
        return Result.ok(map);
    }

    @ApiOperation("新增")
    @PostMapping
    public Result add(@RequestBody Disease disease) {
        long id = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE;
        disease.setId(id);
        diseaseDao.add(disease);
        return Result.ok();
    }

    @ApiOperation("更新")
    @PutMapping("/{id}")
    public Result update(@PathVariable("id") Long id, @RequestBody Disease disease) {
        disease.setId(id);
        diseaseDao.update(disease);
        return Result.ok();
    }

    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Long id) {
        diseaseDao.deleteById(id);
        return Result.ok();
    }
}


